package 网络编程;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketTimeoutException;

/**
 * @author 陈Ser
 * @ClassName temSocket
 * @description: TODO
 * @Date 2021/9/14 16:53
 * @Version 1.0
 */
public class ServerSocket extends Thread {


    private java.net.ServerSocket serverSocket;

    public ServerSocket(int port) throws IOException {
        serverSocket = new java.net.ServerSocket(port);
        serverSocket.setSoTimeout(10000);
    }

    public static void main(String[] args) {

//        int port = Integer.parseInt(args[0]);
        int port = Integer.parseInt("6066");
        try {
            Thread t = new ServerSocket(port);
            t.run();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void run() {
//        while (true)
        {
            try {
                System.out.println("等待远程连接，端口号为：" + serverSocket.getLocalPort() + "...");
                System.out.println("等待远程连接，IP为：" + serverSocket.getInetAddress().getHostAddress());
                Socket server = serverSocket.accept();
                System.out.println("远程主机地址：" + server.getRemoteSocketAddress());

                DataInputStream in = new DataInputStream(server.getInputStream());
                System.out.println(in.readUTF());

                DataOutputStream out = new DataOutputStream(server.getOutputStream());
                out.writeUTF("谢谢连接我：" + server.getLocalSocketAddress() + "\nGoodbye!");

                server.close();
            } catch (SocketTimeoutException s) {
                System.out.println("Socket timed out!");
//                break;
            } catch (IOException e) {
                e.printStackTrace();
//                break;
            }
        }
    }

}
